<template>
  <div>
    <!-- Fixed Header Placeholder -->
    <div class="fixedHeaderPlaceholder___2MMip"></div>

    <!-- Main Generator Section -->
    <section class="generator___16pzX">

      <!-- 导航菜单 -->
      <nav class="cli_nav new-light scene_mobile clearfix">
        <ul class="sub_nav sub_mobile_nav cli_head_container clearfix">
          <li><router-link class="t06971093650622ab_sep on [navigation_text]" to="/qrcode/text" @click="StatisticsData(120,11)" title="生成文本二维码">文本</router-link></li>
          <li><router-link class="tab_sep [navigation_url]" to="/qrcode/url" @click="StatisticsData(120,12)" title="生成网址二维码">网址</router-link></li>
          <li><router-link class="tab_sep [navigation_files]" to="/qrcode/files" @click="StatisticsData(120,13)" title="生成文件二维码">文件</router-link></li>
          <li><router-link class="tab_sep [navigation_img]" to="/qrcode/img" @click="StatisticsData(120,14)" title="生成图片二维码">图片</router-link></li>
          <li><router-link class="tab_sep [navigation_multimedia]" to="/qrcode/multimedia" @click="StatisticsData(120,15)" title="生成音视频二维码">音视频</router-link></li>
          <li><router-link class="tab_sep [navigation_vcard]" to="/qrcode/vcard" @click="StatisticsData(120,16)" title="名片二维码">名片</router-link></li>
          <li><router-link class="tab_sep [navigation_weixin]" to="/qrcode/weixin" @click="StatisticsData(120,17)" title="美化微信二维码">微信</router-link></li>
          <li><router-link class="tab_sep [navigation_form]" to="/qrcode/form" @click="StatisticsData(120,124001)" title="记录表单">表单</router-link></li>
          <li><router-link class="tab_sep [navigation_batch]" to="/qrcode/batch" title="批量生码">批量生码</router-link></li>
          <li><router-link class="tab_sep [navigation_tools]" to="/qrcode/tools" @click="StatisticsData(120,161)" title="更多高级功能">更多工具</router-link></li>
          <li class="pull-right right-nav-items none-after-form">
            <ul>
              <li class="pull-left nav-tool-popover-scan-new">
                <router-link class="template-code" data-analyze="8,118010" to="/qrcode/template" id="__index_template">
                  <i class="clifont anticon-moban1"></i>
                  模板库建码
                </router-link>
              </li>
            </ul>
          </li>
        </ul>
      </nav>

      <!-- Main Container -->
      <section class="nears-responsive-wrapper container___2PQHJ" :style="responsiveWrapperStyle">
        <!-- User Input Area -->
        <section class="percent70 userInputAreaWrapper___1C1Nh">
          <div class="userInputArea___37Y5Q" style="display:block">
            <button class="__nears_primary_1 ant4-btn __nears_primary_1 ant4-btn-dashed advancedEdit___1orjc to-adv-editor-in-textarea"
                    type="button" @click="handleAdvancedEdit">
              <span>高级编辑</span>
            </button>
            <div class="userInput___1IQj5">
              <textarea class="user-input-textarea"
                        placeholder="请输入文字内容"
                        v-model="textContent"
                        @input="handleTextInput"></textarea>
            </div>
          </div>
          <div class="actions___2haOM">
            <button class="__nears_primary_1 ant4-btn __nears_primary_1 ant4-btn-primary __nears_primary_1 ant4-btn-lg mainAction___3-Mj6 generate-main-action"
                    type="button" @click="generateQRCode">
              <span>生成二维码</span>
            </button>
          </div>
        </section>

        <!-- Code Actions Area -->
        <section class="percent30 codeActionsWrapper___2_NeE">
          <div class="actionsWrapper___3jSy0">
            <div class="badgeEntry___1dDWA" :style="{display: showPlaceholder ? 'block' : 'none'}">
              <router-link class="children-pointer-none to-decode-qr" to="/qrcode/deqr">
                <i class="clifont anticon-saomashiyong"></i>
                <span>解码</span>
              </router-link>
            </div>
            <div class="none___1KWtv" style="cursor:pointer" :style="{display: showPlaceholder ? 'block' : 'none'}">
              <img alt="生成二维码" src="../../assets/images/3f5aa5ae0f31.png"/>
            </div>
            <div class="qrStyleEntry___b26Ez" :class="{hidden: !showPlaceholder}" v-show="showPlaceholder">
              <div class="entry___1t0FI">
                <a class="children-pointer-none to-style" href="https://mh.cli.im/" target="_blank">
                  <span class="clifont anticon-meihua"></span>美化
                </a>
              </div>
              <div class="entry___1t0FI">
                <a class="children-pointer-none to-make-label"
                   href="https://console.cli.im/batchLabelSpread?from=cliim-style-tpl-detail&fromKey=online&from_case_type=1&isFromCreateAI=false&label_tplid=2504&paintMaterialId=3&styleSizeId=77&style_tplid=623&tab=Online&fromBatchCreateAbTest=test3&style_create_from=9"
                   target="_blank">
                  <span class="clifont anticon-zhizuobiaoqian"></span>制作标签
                </a>
              </div>
            </div>

            <!-- Generated QR Code Section -->
            <section class="generated___1zUWD" :style="{display: showGenerated ? 'block' : 'none'}">
              <div class="w-full flex items-center space-between mb-12">
                <span class="text-color-primary font-bold">标签样式：基础样式</span>
                <a class="children-pointer-none cliLink to-toggle-style"
                   href="javascript:;"
                   id="toggle_label_style_tpl"
                   rel="noopener noreferrer"
                   @click="toggleStyle">
                  切换<i class="relative top-1 clifont anticon-cli-angle-right"></i>
                </a>
              </div>
              <div style="display:block">
                <div class="qrContainer___2FEvP main-qr-image-container">
                  <img alt="" class="main-qr-image" :src="generatedQRImage"/>
                </div>
              </div>
              <div class="qr-settings-wrapper mt-12 mb-12">
                <select class="qr-settings-select" v-model="selectedSettingOption" @change="handleSettingChange">
                  <option value="summary">{{ qrCodeSettings }}</option>
                  <option value="codeType">码制: {{ codeType }}</option>
                  <option value="errorCorrection">容错率: {{ errorCorrection }}</option>
                  <option value="size">尺寸: {{ qrSize }}</option>
                  <option value="version">码版本: {{ qrVersion }}</option>
                  <option value="margin">码边距: {{ qrMargin }}</option>
                </select>
              </div>
              <div class="w-full actionsGroup1___1mN5c">
                <button class="__nears_primary_1 ant4-btn __nears_primary_1 ant4-btn-default upload-logo-frame"
                        type="button" @click="uploadLogo">
                  <span>上传Logo</span>
                </button>
                <button class="__nears_primary_1 ant4-btn __nears_primary_1 ant4-btn-default to-style-frame"
                        type="button" @click="openStyleFrame">
                  <span>二维码美化</span>
                </button>
              </div>
              <div class="actionsGroup2___xqi8b">
                <button class="__nears_primary_1 ant4-btn __nears_primary_1 ant4-btn-primary download-one"
                        type="button" @click="downloadQRCode">
                  <span>下载图片</span>
                </button>
              </div>
              <div class="actionsGroup3___XiCVq">
                <a class="bottomText___3LxqN layout-to-paper"
                   href="javascript:;"
                   rel="noopener noreferrer"
                   @click="layoutToPaper">排版到A4纸上</a>
                <a class="bottomText___3LxqN export-label"
                   href="javascript:;"
                   rel="noopener noreferrer"
                   @click="exportLabel">下载其他格式</a>
              </div>
              
              <!-- Chinese WeChat Notice -->
              <div class="wechat-notice mt-8 text-xs text-orange-600 bg-orange-50 p-3 rounded">
                <span>⚠️ 微信不支持展示二维码中的中文，可 </span>
                <a class="text-blue-600 underline" href="javascript:;" @click="convertToActiveCode">转化为活码</a>
              </div>
            </section>
          </div>
        </section>
      </section>

      <!-- Bottom Tabs Section -->
      <section class="nears-responsive-wrapper" :style="responsiveWrapperStyle">
        <div class="__nears_primary_1 ant4-tabs __nears_primary_1 ant4-tabs-top ant4-tabs-nav-without-under-line w-full ant4-tabs-tab-gap-40 ant4-tabs-nav-bottom-gap-0">
          <div class="__nears_primary_1 ant4-tabs-nav" role="tablist">
            <div class="__nears_primary_1 ant4-tabs-nav-wrap">
              <div class="__nears_primary_1 ant4-tabs-nav-list" style="transform:translate(0px, 0px)">
                <div class="__nears_primary_1 ant4-tabs-tab __nears_primary_1 ant4-tabs-tab-active"
                     data-node-key="/text"
                     @click="switchTab('/text')">
                  <div aria-selected="true" class="__nears_primary_1 ant4-tabs-tab-btn" role="tab" tabindex="0">
                    功能介绍
                  </div>
                </div>
                <div class="__nears_primary_1 ant4-tabs-tab"
                     data-node-key="/text/other"
                     style="margin-left:40px"
                     @click="switchTab('/text/other')">
                  <div aria-selected="false" class="__nears_primary_1 ant4-tabs-tab-btn" role="tab" tabindex="0">
                    最近建码
                  </div>
                </div>
                <div class="__nears_primary_1 ant4-tabs-tab"
                     data-node-key="/text/comment"
                     style="margin-left:40px"
                     @click="switchTab('/text/comment')">
                  <div aria-selected="false" class="__nears_primary_1 ant4-tabs-tab-btn" role="tab" tabindex="0">
                    讨论(67)
                  </div>
                </div>
                <div class="__nears_primary_1 ant4-tabs-ink-bar"></div>
              </div>
            </div>
            <div class="__nears_primary_1 ant4-tabs-nav-operations __nears_primary_1 ant4-tabs-nav-operations-hidden">
              <button aria-controls="null-more-popup"
                      aria-expanded="false"
                      aria-haspopup="listbox"
                      aria-hidden="true"
                      class="__nears_primary_1 ant4-tabs-nav-more"
                      id="null-more"
                      style="margin-left:40px;visibility:hidden;order:1"
                      tabindex="-1"
                      type="button">
                <span aria-label="ellipsis" class="anticon anticon-ellipsis" role="img">
                  <svg aria-hidden="true" data-icon="ellipsis" fill="currentColor" focusable="false" height="1em" viewbox="64 64 896 896" width="1em">
                    <path d="M176 511a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0zm280 0a56 56 0 10112 0 56 56 0 10-112 0z"></path>
                  </svg>
                </span>
              </button>
            </div>
          </div>
          <div class="__nears_primary_1 ant4-tabs-content-holder">
            <div class="__nears_primary_1 ant4-tabs-content __nears_primary_1 ant4-tabs-content-top">
              <div aria-hidden="false"
                   class="__nears_primary_1 ant4-tabs-tabpane __nears_primary_1 ant4-tabs-tabpane-active intro-tab"
                   role="tabpanel"
                   tabindex="0">
              </div>
            </div>
          </div>
        </div>
      </section>
    </section>

    <!-- Tab Content Wrapper -->
    <div class="tabContentWrapper___1AvR8">
      <!-- Wiki Tab Content -->
      <div id="tab-wiki" :style="{display: currentTab === '/text' ? 'block' : 'none'}">
        <section class="nears-responsive-wrapper" :style="responsiveWrapperStyle">
          <section class="percent70">
            <div class="wiki" style="margin:40px 0">
              <p><strong>文本码</strong>：能将字符串（如序列号、产品信息、网址、编码等）直接转化为二维码，在各业务流程中实现信息的高效录入、传递与追溯，有效提升效率并降低出错率。</p>
              <p>例如：将产品序列号、批次号、生产日期等关键信息生成二维码并粘贴在产品或包装上。在质检、入库、出库、售后等环节，通过扫码即可获取或录入对应信息，避免人工输入错误，实现高效的追溯管理。</p>
              <p><strong>文本码完全免费，不限生码数量，二维码长期有效</strong>。</p>
              <h2>核心功能</h2>
              <h3>支持多种码制</h3>
              <p>草料平台提供四种主流码制。<strong>平台生成的二维码默认为QR码</strong>，你也可以根据不同应用需求切换为其他码制。<a href="help/77753.html" title="详细了解码制">详细了解码制</a></p>
              <ul>
                <li><strong>QR Code</strong>：广泛应用于信息存储、产品展示、商品标识、支付和广告等。</li>
                <li><strong>汉信码</strong>：由中国物品编码中心开发，具备强大的汉字编码能力，适用于政府办公和食品安全等领域。</li>
                <li><strong>PDF417</strong>：适合大容量、高可靠性的信息存储，如证件管理、执照年检和票据管理。</li>
                <li><strong>Data Matrix</strong>：信息密度高，适用于小型物品追踪与标识，如电子元器件和医疗器械。</li>
              </ul>
              <h3>容错率设置</h3>
              <p>提供四级容错率，确保二维码在部分损坏或遮挡情况下仍可扫描。推荐使用 H级（30%） ，保障二维码在运输和使用过程中的数据完整性。<a href="help/57415.html" title="了解详情">详细了解容错率</a></p>
              <p>可选容错率：L（7%）、M（15%）、Q（25%）、H（30%）</p>
              <h3>多种尺寸和下载格式</h3>
              <ul>
                <li>支持300×300、400×400等常用尺寸，也可自定义二维码图片尺寸。</li>
                <li>下载格式包括PNG图片、PDF矢量、SVG矢量、EPS矢量等，满足不同使用需求。</li>
              </ul>
              <h2>更多实用功能</h2>
              <h3>批量生码</h3>
              <p>支持在线输入或导入 Excel 表格，自动为每行数据生成二维码，适合大规模生码需求。<a href="batch.html" title="前往批量生码">前往批量生码</a></p>
              <h3>二维码标签制作</h3>
              <p>提供 150 多种标签样式，支持内容修改、批量制作与排版管理，支持 PNG、PDF 等多种下载格式。生成的二维码标签可在后台随时下载补打。<a href="label.html" title="制作标签">制作标签</a></p>
              <p>草料还提供了二维码标签印刷服务，支持快速下单，最快当日发货。质量问题免费重印，确保顺利部署。<a href="print/service.html" title="了解印刷服务">了解印刷服务</a></p>
              <h3>无痕生码</h3>
              <p>针对含有敏感信息（如密钥）的二维码，提供本地编码工具，确保数据不通过网络传输，保障信息安全。<a href="https://s.cli.im/" title="前往无痕生码">前往无痕生码</a></p>
              <h2>进阶应用：制作活码</h2>
              <p>如果希望在二维码中添加更多信息，如图片、音视频、文件、表单等，可使用「活码」功能。<a href="https://console.cli.im/nedit?jumpFrom=frontText&create_from=42&pageFrom=frontBuild&action=frontText&is_create_code=0&paste_key=" title="进入高级编辑器">生成活码</a></p>
              <p><strong>主要特点</strong></p>
              <ul>
                <li>随时更新二维码内容，二维码图案不变，长期有效</li>
                <li>支持添加图片、文件、富文本等各种内容</li>
                <li>支持统计扫描量数据</li>
              </ul>
              <p>通过草料平台，你还可以搭建二维码业务系统，低成本实现产品介绍、签到报名、设备巡检等多种应用需求。<a href="template.html" title="前往模板库">前往模板库</a></p>
            </div>
          </section>
          <section class="percent30">
            <div class="wikiOutlineWrapper" ref="outlineWrapper">
              <ul class="wikiOutlineContainer" ref="outlineContainer">
                <li v-for="(item, index) in outlineItems"
                    :key="index"
                    :class="['item', { active: activeOutlineIndex === index }]"
                    :data-target-header="item.tagName"
                    @click="scrollToHeader(item, index)">
                  <span>{{ item.text }}</span>
                </li>
              </ul>
            </div>
          </section>
        </section>
      </div>

      <!-- History Tab Content -->
      <div id="tab-history" :style="{display: currentTab === '/text/other' ? 'block' : 'none'}">
        <section class="nears-responsive-wrapper bottomSets___1cwQW" :style="bottomSetsStyle">
          <section class="percent70 historyWrapper___V-3Om">
            <section>
              <div class="header___92UTU">
                <div class="summary___3Y6j7">共 {{ historyCount }} 个</div>
                <div class="actions___2V9eB">
                  <a class="action___3rd2l portal-auto-save-text-code-to-account-switch"
                     href="javascript:;"
                     rel="noopener noreferrer"
                     @click="toggleAutoSave">
                    <button :aria-checked="autoSave"
                            class="__nears_primary_1 ant4-switch __nears_primary_1 ant4-switch-small"
                            role="switch"
                            type="button">
                      <div class="__nears_primary_1 ant4-switch-handle"></div>
                      <span class="__nears_primary_1 ant4-switch-inner"></span>
                    </button>  自动保存到帐号
                  </a>
                  <span class="action___3rd2l delete-all" @click="deleteAllHistory">
                    <i class="clifont anticon-new-delete"></i>删除全部
                  </span>
                  <span class="action___3rd2l download-all" @click="downloadAllHistory">
                    <i class="clifont anticon-xiazai1"></i>下载全部
                  </span>
                </div>
              </div>
              <div class="whenEmpty___3Zofp" v-if="historyCount === 0">暂无历史建码数据</div>
              <!-- History items would be rendered here -->
            </section>
          </section>
          <section class="percent30 introduce___CFwRb">
            <div style="margin-top:36px">
              <div class="container___2Gm4i">
                <h2 class="blockTitle___k55n-">文本码推荐模板</h2>
                <p class="blockDesc___2JGiK">搭配多种功能组件，满足更多场景需求
                  <a class="cliLink" href="template.html" target="_blank">查看全部模板</a>
                </p>
                <div class="linkList___bu0Re">
                  <div class="row___3YSVU">
                    <a class="recTplItem___3V-1B" href="template/detail/38373533.html" target="_blank">
                      <h3 class="title___2F4Yk">产品详情介绍</h3>
                    </a>
                    <a class="recTplItem___3V-1B" href="template/detail/121462970.html" target="_blank">
                      <h3 class="title___2F4Yk">溯源信息展示</h3>
                    </a>
                  </div>
                  <div class="row___3YSVU">
                    <a class="recTplItem___3V-1B" href="template/detail/228555.html" target="_blank">
                      <h3 class="title___2F4Yk">固定资产标签</h3>
                    </a>
                    <a class="recTplItem___3V-1B" href="template/detail/30172739.html" target="_blank">
                      <h3 class="title___2F4Yk">出入库登记</h3>
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </section>
      </div>

      <!-- Forum/Comment Tab Content -->
      <section class="nears-responsive-wrapper"
               :style="{...responsiveWrapperStyle, flexDirection: 'column', display: currentTab === '/text/comment' ? 'flex' : 'none'}">
        <div class="__nears_primary_1 ant4-spin-nested-loading">
          <div>
            <div aria-busy="true" aria-live="polite" class="__nears_primary_1 ant4-spin __nears_primary_1 ant4-spin-spinning">
              <span class="__nears_primary_1 ant4-spin-dot __nears_primary_1 ant4-spin-dot-spin">
                <i class="__nears_primary_1 ant4-spin-dot-item"></i>
                <i class="__nears_primary_1 ant4-spin-dot-item"></i>
                <i class="__nears_primary_1 ant4-spin-dot-item"></i>
                <i class="__nears_primary_1 ant4-spin-dot-item"></i>
              </span>
            </div>
          </div>
          <div class="__nears_primary_1 ant4-spin-container __nears_primary_1 ant4-spin-blur">
            <section class="forumHeader___3fy-N">
              <h3>所有讨论</h3>
              <a class="__nears_primary_1 ant4-btn __nears_primary_1 ant4-btn-primary"
                 href="community/create_post.html"
                 target="_blank">
                <span>发 帖</span>
              </a>
            </section>
            <div id="text-mini-forum-container" style="opacity:0"></div>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import QRCode from 'qrcode'

// Component state
const textContent = ref('')
const showGenerated = ref(false)
const showPlaceholder = ref(true)
const generatedQRImage = ref('')
const currentTab = ref('/text')
const historyCount = ref(0)
const autoSave = ref(false)

// QR Code settings
const codeType = ref('QR Code')
const errorCorrection = ref('H级(30%)')
const qrSize = ref('600x600px')
const qrVersion = ref('1 (21*21模块)')
const qrMargin = ref('3个颜色块')
const selectedSettingOption = ref('summary')

// Outline navigation state
const outlineItems = ref<Array<{ text: string, tagName: string, element: HTMLElement }>>([])
const activeOutlineIndex = ref(-1)
const isScrolling = ref(false)
const outlineWrapper = ref<HTMLElement>()
const outlineContainer = ref<HTMLElement>()

// Computed styles
const responsiveWrapperStyle = computed(() => ({
  maxWidth: '1250px',
  width: 'px',
  minWidth: '0px',
  margin: '0 auto',
  paddingLeft: '24px',
  paddingRight: '24px'
}))

const bottomSetsStyle = computed(() => ({
  ...responsiveWrapperStyle.value,
  margin: '16px auto'
}))

const defaultQRImage = computed(() => {
  return import('../../assets/images/3f5aa5ae0f31.png')
})

const qrCodeSettings = computed(() => {
  return `${codeType.value}，${errorCorrection.value}，${qrSize.value}`
})

// Component methods
const handleAdvancedEdit = () => {
  // Navigate to advanced editor
  console.log('Advanced edit clicked')
}

const handleTextInput = (event: Event) => {
  const target = event.target as HTMLTextAreaElement
  textContent.value = target.value
}

const generateQRCode = async () => {
  if (!textContent.value.trim()) {
    alert('请输入文字内容')
    return
  }

  try {
    // Generate QR code with specified options
    const options = {
      errorCorrectionLevel: 'H',  // 30% error correction
      width: 600,                 // 600x600 pixels
      margin: 3,                  // 3 color blocks margin
      color: {
        dark: '#000000',          // Black modules
        light: '#FFFFFF'          // White background
      }
    }

    // Generate QR code as data URL
    const qrDataURL = await QRCode.toDataURL(textContent.value, options)
    
    // Hide placeholder image and show generated QR code section
    showPlaceholder.value = false
    showGenerated.value = true
    generatedQRImage.value = qrDataURL
    
    console.log('QR code generated successfully for:', textContent.value)
  } catch (error) {
    console.error('Failed to generate QR code:', error)
    alert('生成二维码失败，请重试')
  }
}

const toggleStyle = () => {
  console.log('Toggle style clicked')
}

const uploadLogo = () => {
  console.log('Upload logo clicked')
}

const openStyleFrame = () => {
  console.log('Open style frame clicked')
}

const downloadQRCode = () => {
  if (!showGenerated.value) {
    alert('请先生成二维码')
    return
  }
  console.log('Download QR code clicked')
}

const layoutToPaper = () => {
  console.log('Layout to paper clicked')
}

const exportLabel = () => {
  console.log('Export label clicked')
}

const switchTab = (tab: string) => {
  currentTab.value = tab
  console.log('Switched to tab:', tab)
}

const toggleAutoSave = () => {
  autoSave.value = !autoSave.value
  console.log('Auto save:', autoSave.value)
}

const deleteAllHistory = () => {
  console.log('Delete all history clicked')
}

const downloadAllHistory = () => {
  console.log('Download all history clicked')
}

const convertToActiveCode = () => {
  console.log('Convert to active code clicked')
  // Navigate to active code generator
}

const handleSettingChange = (event: Event) => {
  const target = event.target as HTMLSelectElement
  const selectedValue = target.value
  
  console.log('Settings changed to:', selectedValue)
  
  // Show the selected setting details briefly, then reset to summary
  if (selectedValue !== 'summary') {
    // You can add specific logic here for different setting types
    switch (selectedValue) {
      case 'codeType':
        console.log('Code type setting selected:', codeType.value)
        break
      case 'errorCorrection':
        console.log('Error correction setting selected:', errorCorrection.value)
        break
      case 'size':
        console.log('Size setting selected:', qrSize.value)
        break
      case 'version':
        console.log('Version setting selected:', qrVersion.value)
        break
      case 'margin':
        console.log('Margin setting selected:', qrMargin.value)
        break
    }
    
    // Reset to summary after 2 seconds
    setTimeout(() => {
      selectedSettingOption.value = 'summary'
    }, 2000)
  }
}

// Outline navigation functions
const initOutlineNavigation = () => {
  nextTick(() => {
    collectHeaders()
    setupScrollListener()
  })
}

const collectHeaders = () => {
  // Collect only h2 elements from the wiki content
  const headers = document.querySelectorAll('.wiki h2')
  outlineItems.value = Array.from(headers).map((header: HTMLElement) => ({
    text: header.textContent || '',
    tagName: header.tagName,
    element: header
  }))
  
  // Set the first item as active by default
  if (outlineItems.value.length > 0) {
    activeOutlineIndex.value = 0
  }

  // Show or hide outline container based on whether there are headers
  if (outlineWrapper.value) {
    if (outlineItems.value.length > 0) {
      outlineWrapper.value.style.display = 'block'
      outlineContainer.value?.classList.add('hasOutline')
    } else {
      outlineWrapper.value.style.display = 'none'
      outlineContainer.value?.classList.remove('hasOutline')
    }
  }

  // Sync initial state
  syncActiveHeader()
}

const setupScrollListener = () => {
  const throttledSync = throttle(syncActiveHeader, 200)
  window.addEventListener('scroll', throttledSync)

  // Store cleanup function
  scrollCleanup = () => {
    window.removeEventListener('scroll', throttledSync)
  }
}

const syncActiveHeader = () => {
  if (isScrolling.value || outlineItems.value.length === 0) return

  let activeIndex = 0 // Default to first item
  const scrollTop = window.scrollY
  const headerOffsetTop = 100 // Offset for header detection

  // Find the current active header based on scroll position
  for (let i = 0; i < outlineItems.value.length; i++) {
    const element = outlineItems.value[i].element
    const elementTop = element.offsetTop - headerOffsetTop
    
    if (scrollTop >= elementTop) {
      activeIndex = i
    } else {
      break
    }
  }

  activeOutlineIndex.value = activeIndex
}

const isElementScrolled = (element: HTMLElement): boolean => {
  const viewHeight = window.innerHeight
  return element.getBoundingClientRect().top < (viewHeight - viewHeight * 0.6)
}

const scrollToHeader = (item: { element: HTMLElement, text: string }, index: number) => {
  if (activeOutlineIndex.value === index || isScrolling.value) return

  activeOutlineIndex.value = index
  isScrolling.value = true

  // Smooth scroll to the target header
  const offsetTop = item.element.offsetTop
  window.scrollTo({
    top: offsetTop,
    behavior: 'smooth'
  })

  // Reset scrolling flag after animation
  setTimeout(() => {
    isScrolling.value = false
  }, 800)
}

const throttle = (fn: Function, threshold: number) => {
  let last = 0
  let timer: NodeJS.Timeout | null = null

  return function (...args: any[]) {
    const now = Date.now()

    if (now - last < threshold) {
      if (timer) clearTimeout(timer)
      timer = setTimeout(() => {
        fn.apply(this, args)
        last = Date.now()
      }, threshold)
      return
    }

    last = now
    return fn.apply(this, args)
  }
}

let scrollCleanup: (() => void) | null = null

// Initialize page functionality
const initializePage = () => {
  // Set up router base
  (window as any).routerBase = "/"

  // Initialize context
  const ssrContext = {
    user: null,
    renderAt: Date.now(),
    hitCache: 2,
    referer: "",
    userAgent: navigator.userAgent
  }
  ;(window as any).__ssr_context = ssrContext

  console.log('Page initialized')
}

// Lifecycle hooks
onMounted(() => {
  initializePage()

  // Initialize outline navigation
  initOutlineNavigation()

  // Load external scripts if needed
  loadExternalScripts()
})

onUnmounted(() => {
  // Cleanup scroll listener
  if (scrollCleanup) {
    scrollCleanup()
  }
})

const loadExternalScripts = () => {
  // This function would handle loading external scripts
  // For now, we'll just log that scripts would be loaded
  console.log('External scripts would be loaded here')

  // Original script loading logic would be adapted here:
  // - cat-mini.js
  // - volcano.js
  // - portal-analysis.js
  // - Other required scripts
}
</script>

<style src="../../assets/css/b76aaf663b7f.css" scoped/>
<style src="../../assets/css/5e6b9bf9fd2f.css" scoped/>
<style src="../../assets/css/2034b15460f1.css" scoped/>
<style src="../../assets/css/b64637f7e36e.css" scoped/>


<style scoped>
/* Additional component-specific styles can be added here */
.user-input-textarea {
  width: 100%;
  min-height: 120px;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
}

.user-input-textarea:focus {
  border-color: #40a9ff;
  outline: 0;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}



/* QR Style Entry Layout Fix */
.qrStyleEntry___b26Ez {
  display: flex !important;
  justify-content: space-between !important;
  gap: 12px !important;
  align-items: center !important;
}

.qrStyleEntry___b26Ez .entry___1t0FI {
  flex: 1 !important;
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
}

/* Hidden state */
.qrStyleEntry___b26Ez.hidden,
.qrStyleEntry___b26Ez[style*="display: none"] {
  display: none !important;
}

/* QR Settings Wrapper */
.qr-settings-wrapper {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* QR Settings Select Dropdown */
.qr-settings-select {
  width: 100%;
  height: 32px;
  border: 1px solid #d9d9d9;
  background: white;
  color: #666;
  font-size: 14px;
  font-family: inherit;
  outline: none;
  cursor: pointer;
  padding: 0 12px;
  border-radius: 6px;
  line-height: 32px;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  background-image: url('data:image/svg+xml;charset=US-ASCII,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 5"><path fill="%23666" d="m0 0l2 2 2-2z"/></svg>');
  background-repeat: no-repeat;
  background-position: right 12px center;
  background-size: 12px;
  padding-right: 32px;
}

.qr-settings-select::-ms-expand {
  display: none;
}

.qr-settings-select:focus {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.qr-settings-select option {
  background: white;
  color: #333;
  padding: 8px 12px;
  font-size: 12px;
}

/* WeChat Notice Styling */
.wechat-notice {
  border-left: 4px solid #ff8c00;
}

/* Ensure responsive behavior */
@media (max-width: 768px) {
  .percent70 {
    width: 100% !important;
  }

  .percent30 {
    width: 100% !important;
    margin-top: 20px;
  }
  
  .qrStyleEntry___b26Ez {
    flex-direction: column;
    gap: 8px;
  }
}
</style>

